package com.xoa.global.timedTask;

import com.tencent.xinge.*;
import com.xoa.dao.common.SysParaMapper;
import com.xoa.model.attend.AttendSet;
import com.xoa.model.common.SysPara;
import com.xoa.model.users.Users;
import com.xoa.service.attend.AttendSetService;
import com.xoa.service.calendar.CalendarService;
import com.xoa.service.users.UsersService;
import com.xoa.util.DateFormat;
import com.xoa.util.common.StringUtils;
import com.xoa.util.ipUtil.MachineCode;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by 刘建 on 2020/7/12 15:16
 * 定时任务-消息推送
 */
@Component
public class MessagePush {

    @Autowired
    AttendSetService articleService;

    @Autowired
    CalendarService calendarService;

    @Autowired
    UsersService usersService;

    @Resource
    SysParaMapper sysParaMapper;

    @Value("${xg_push_msg_android_key}")
    private String androidKey;

    @Value("${xg_push_msg_android_sercetkey}")
    private String  androidSercetKey;

    @Value("${xg_push_msg_ios_key}")
    private String iosKey;

    @Value("${xg_push_msg_ios_sercetkey}")
    private String iosSercetKey;
    /**
     * 定时推送消息方法
     */
    public void springQtzBean(Integer oid, Date date) throws Exception {
        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
        String dateto = dateFormat.format(date);
        String jixiema = this.getMachineCode12();
        List<Users> users=usersService.LoginUserList();
        for (Users users1:users){
            if(users1.getDutyType()!=0){
                AttendSet attendSet= articleService.queryAttendSetByTuiSongId(users1.getUid());
                if(attendSet!=null){
                    Calendar nowDate = Calendar.getInstance();// 创建 Calendar 对象
                    if("1".equals(attendSet.getAtime1Setother())){ //如果开启
                        if("1".equals(attendSet.getCommute1())){
                            Date  date2= DateFormat.getDateTimes(attendSet.getAtime1());//获取签到标准时间
                            nowDate.setTime(date2);
                            nowDate.add(Calendar.MINUTE, -10);
                            String dateStr = dateFormat.format(nowDate.getTime());
                            if(dateto.equals(dateStr)){
                                //根据uid 查询userId
                                String account = jixiema + users1.getUserId() + oid;
                                tuiSongXhH(account);
                            }
                        }

                    }
                    if("1".equals(attendSet.getAtime2Setother())){
                        if("1".equals(attendSet.getCommute2())){
                            Date  date2=DateFormat.getDateTimes(attendSet.getAtime2());//获取签到标准时间
                            nowDate.setTime(date2);
                            nowDate.add(Calendar.MINUTE, -10);
                            String dateStr = dateFormat.format(nowDate.getTime());
                            if(dateto.equals(dateStr)){
                                //根据uid 查询userId
                                String account = jixiema + users1.getUserId() + oid;
                                tuiSongXhH(account);
                            }
                        }

                    }
                    if("1".equals(attendSet.getAtime3Setother())){
                        if("1".equals(attendSet.getCommute3())){
                            Date  date2=DateFormat.getDateTimes(attendSet.getAtime3());//获取签到标准时间
                            nowDate.setTime(date2);
                            nowDate.add(Calendar.MINUTE, -10);
                            String dateStr = dateFormat.format(nowDate.getTime());
                            if(dateto.equals(dateStr)){
                                //根据uid 查询userId
                                String account = jixiema + users1.getUserId() + oid;
                                tuiSongXhH(account);
                            }
                        }


                    }
                    if("1".equals(attendSet.getAtime4Setother())){
                        if("1".equals(attendSet.getCommute4())){
                            Date  date2=DateFormat.getDateTimes(attendSet.getAtime4());//获取签到标准时间
                            nowDate.setTime(date2);
                            nowDate.add(Calendar.MINUTE, -10);
                            String dateStr = dateFormat.format(nowDate.getTime());
                            if(dateto.equals(dateStr)){
                                //根据uid 查询userId
                                String account = jixiema + users1.getUserId() + oid;
                                tuiSongXhH(account);
                            }
                        }


                    }
                    if("1".equals(attendSet.getAtime5Setother())){
                        if("1".equals(attendSet.getCommute5())){
                            Date  date2=DateFormat.getDateTimes(attendSet.getAtime5());//获取签到标准时间
                            nowDate.setTime(date2);
                            nowDate.add(Calendar.MINUTE, -10);
                            String dateStr = dateFormat.format(nowDate.getTime());
                            if(dateto.equals(dateStr)){
                                //根据uid 查询userId
                                String account = jixiema + users1.getUserId() + oid;
                                tuiSongXhH(account);
                            }
                        }


                    }
                    if("1".equals(attendSet.getAtime6Setother())){
                        if("1".equals(attendSet.getCommute6())){
                            Date  date2=DateFormat.getDateTimes(attendSet.getAtime6());//获取签到标准时间
                            nowDate.setTime(date2);
                            nowDate.add(Calendar.MINUTE, -10);
                            String dateStr = dateFormat.format(nowDate.getTime());
                            if(dateto.equals(dateStr)){
                                //根据uid 查询userId
                                String account = jixiema + users1.getUserId() + oid;
                                tuiSongXhH(account);
                            }
                        }

                    }
                }
            }
        }
    }

    //日程安排消息推送
    public void riCheng(Integer oid, Date date) throws Exception {
        List<com.xoa.model.calender.Calendar> attendSet = calendarService.rChSelect();
        Calendar calendar = Calendar.getInstance();
        String jixiema = this.getMachineCode12();
        for (com.xoa.model.calender.Calendar calendar1 : attendSet) {
            String account[] = null;
            String content = calendar1.getContent();
            String beforeRemaind = calendar1.getBeforeRemaind();
            if (beforeRemaind != null) {
                String[] time = beforeRemaind.split("\\|");
                if ((!StringUtils.checkNull(time[0]))&&(!time[0].equals("0")) && (time[0] != null)) {
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    calendar.setTime(date);
                    calendar.add(Calendar.DAY_OF_MONTH, +(Integer.valueOf(time[0])));
                    Date date1 = calendar.getTime();
                    String dateString = dateFormat.format(date1);
                    if ((!StringUtils.checkNull(time[1]))&&(!time[1].equals("0")) && time[1] != null) {
                        calendar.setTime(date1);
                        calendar.add(Calendar.HOUR_OF_DAY, +(Integer.valueOf(time[1])));
                        date1 = calendar.getTime();
                        String date1String=dateFormat.format(date1);
                        if ((!time[2].equals("0")) && time[2] != null) {
                            calendar.setTime(date1);
                            calendar.add(Calendar.MINUTE, +(Integer.valueOf(time[2])));
                            date1 = calendar.getTime();
                            date1String=dateFormat.format(date1);
                            //过滤数据
                            if(calendar1.getCalTime()!=null){
                                String sd = dateFormat.format(new Date(Long.parseLong(calendar1.getCalTime().toString())*1000));
                                if (sd.equals(date1String)) {
                                    account = xunHuanPingJie(calendar1.getOwner(),calendar1.getUserId(), calendar1.getTaker(), oid, jixiema);
                                    tuiSongXh(account, content);
                                }}
                        } else {
                            //过滤数据
                            if(calendar1.getCalTime()!=null){
                                String sd = dateFormat.format(new Date(Long.parseLong(calendar1.getCalTime().toString())*1000));
                                if (sd.equals(date1String)) {
                                    account = xunHuanPingJie(calendar1.getOwner(),calendar1.getUserId(), calendar1.getTaker(), oid, jixiema);
                                    tuiSongXh(account, content);
                                }}
                        }
                    } else {
                        if ((!StringUtils.checkNull(time[2]))&&(!time[2].equals("0")) && time[2] != null) {
                            calendar.setTime(date1);
                            calendar.add(Calendar.MINUTE, -(Integer.valueOf(time[2])));
                            date1 = calendar.getTime();
                            String date1String=dateFormat.format(date1);
                            //过滤数据
                            if(calendar1.getCalTime()!=null){
                                String sd = dateFormat.format(new Date(Long.parseLong(calendar1.getCalTime().toString())*1000));
                                if (sd.equals(date1String)) {
                                    account = xunHuanPingJie(calendar1.getOwner(),calendar1.getUserId(), calendar1.getTaker(), oid, jixiema);
                                    tuiSongXh(account, content);
                                }}
                        } else {
                            if(calendar1.getCalTime()!=null){
                                String sd = dateFormat.format(new Date(Long.parseLong(calendar1.getCalTime().toString())*1000));
                                if (sd.equals(dateString)) {
                                    account = xunHuanPingJie(calendar1.getOwner(),calendar1.getUserId(), calendar1.getTaker(), oid, jixiema);
                                    tuiSongXh(account, content);
                                }}
                        }
                    }
                } else if ((!StringUtils.checkNull(time[1]))&&(!time[1].equals("0")) && time[1] != null) {
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    calendar.setTime(date);
                    calendar.add(Calendar.HOUR_OF_DAY, +(Integer.valueOf(time[1])));
                    Date date1 = calendar.getTime();
                    String date1String=dateFormat.format(date1);
                    if ((!time[2].equals("0")) && time[2] != null) {
                        calendar.setTime(date1);
                        calendar.add(Calendar.MINUTE, +(Integer.valueOf(time[2])));
                        date1 = calendar.getTime();
                        date1String=dateFormat.format(date1);
                        date1=dateFormat.parse(date1String);
                        date1String=dateFormat.format(date1);
                        //过滤数据
                        if(calendar1.getCalTime()!=null){
                            String sd = dateFormat.format(new Date(Long.parseLong(calendar1.getCalTime().toString())*1000));
                            if (sd.equals(date1String)) {
                                account = xunHuanPingJie(calendar1.getOwner(),calendar1.getUserId(), calendar1.getTaker(), oid, jixiema);
                                tuiSongXh(account, content);
                            }}
                    } else {
                        if(calendar1.getCalTime()!=null){
                            String sd = dateFormat.format(new Date(Long.parseLong(calendar1.getCalTime().toString())*1000));
                            if (sd.equals(date1String)) {
                                account = xunHuanPingJie(calendar1.getOwner(),calendar1.getUserId(), calendar1.getTaker(), oid, jixiema);
                                tuiSongXh(account, content);
                            }}
                    }
                } else if ((!StringUtils.checkNull(time[2]))&&(!time[2].equals("0")) && time[2] != null) {
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    calendar.setTime(date);
                    calendar.add(Calendar.MINUTE, +(Integer.valueOf(time[2])));
                    Date date1 = calendar.getTime();
                    String date1String=dateFormat.format(date1);
                    //过滤数据
                    if(calendar1.getCalTime()!=null){
                        String sd = dateFormat.format(new Date(Long.parseLong(calendar1.getCalTime().toString())*1000));
                        if (sd.equals(date1String)) {
                            account = xunHuanPingJie(calendar1.getOwner(),calendar1.getUserId(), calendar1.getTaker(), oid, jixiema);
                            tuiSongXh(account, content);
                        }}
                } else {
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    calendar.setTime(date);
                    String dateString = dateFormat.format(date);
                    //过滤数据
                    if(calendar1.getCalTime()!=null){
                        String sd = dateFormat.format(new Date(Long.parseLong(calendar1.getCalTime().toString())*1000));
                        if (sd.equals(dateString)) {
                            account = xunHuanPingJie(calendar1.getOwner(),calendar1.getUserId(), calendar1.getTaker(), oid, jixiema);
                            tuiSongXh(account, content);
                        }}
                }
            }
        }
    }

    public Date getTime(String datemon) {
        Date time = null;
        try {
            Calendar calendar = Calendar.getInstance();
            // 对 calendar 设置时间的方法
            // 设置传入的时间格式
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
            // 指定一个日期
            Date date = dateFormat.parse(dateFormat1.format(new Date()) + " " + datemon);
            // 对 calendar 设置为 date 所定的日期
            calendar.add(Calendar.MINUTE, +10);//将时间提前10分钟
            calendar.setTime(date);
            time = calendar.getTime();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return time;
    }


    public static String getTimeByMinute(int minute) {

        Calendar calendar = Calendar.getInstance();

        calendar.add(Calendar.MINUTE, minute);

        return new SimpleDateFormat("yyyy-MM-dd HH:mm").format(calendar.getTime());

    }

    //字符串截取循环拼接
    public String[] xunHuanPingJie(String owner, String userId,String taker, Integer oid, String jixiema) {
        String[] contGet = null;
        String owners[] = null;
        owner = owner + taker+","+userId;
        if (owner != null) {
            owners = owner.split(",");
            owners=getDistinct(owners);//去重复
        }
        contGet = new String[owners.length + 1];
        for (int i = 0; i < owners.length; i++) {
            contGet[i] = jixiema + owners[i] + oid;
        }
        return contGet;
    }

    //循环推送 日程提醒
    public void tuiSongXh(String account[], String content) throws JSONException {
        for (int i = 0; i < account.length; i++) {
            if(account[i]!=null){
                //   XingeApp.pushAccountAndroid(2100270598L, "82378f499570aeb8c169fa570cc33508", "日程提醒", content, account[i]);
                XingeApp pushAndroid = new XingeApp(Long.getLong(androidKey), androidSercetKey);//安卓
                XingeApp  push =new XingeApp(Long.getLong(iosKey),iosSercetKey);
                ClickAction clickAction=new ClickAction();
                clickAction.setActionType(ClickAction.TYPE_ACTIVITY);
                clickAction.setActivity("123");
                Style style = new Style(0, 1, 1, 1, 1, 1, 0, 1);
                Message mess = new Message();
                mess.setType(Message.TYPE_NOTIFICATION);
                mess.setStyle(style);
                mess.setTitle("日程提醒");
                mess.setContent(content);
                mess.setAction(clickAction);
                JSONObject ret = pushAndroid.pushSingleAccount (0, account[i], mess);
                JSONObject contentTest = new JSONObject();
                JSONObject obj = new JSONObject();
                JSONObject aps = new JSONObject();
                contentTest.put("title", "日程提醒");//标题
                contentTest.put("body", content);//内容
                aps.put("badge", 1);
                aps.put("alert", contentTest);
                aps.put("sound", "beep.wav");
                obj.put("aps", aps);
                MessageIOS messageIOS=new MessageIOS();
                messageIOS.setRaw(obj.toString());

                JSONObject ret3 =push.pushSingleAccount(0,account[i],messageIOS,XingeApp.IOSENV_PROD);
                //  XingeApp.pushAccountIos(Long.getLong(getIosKey()),getIosSercetKey(), content, account[i], XingeApp.IOSENV_PROD);
            }
        }
    }

    //推送 签到
    public void tuiSongXhH(String account) throws JSONException {
        //  XingeApp.pushAccountAndroid(2100270598L, "82378f499570aeb8c169fa570cc33508", "考勤签到提醒", "离上班时间还有10分钟", account);
        XingeApp pushAndroid = new XingeApp(Long.getLong(androidKey), androidSercetKey);//安卓
        XingeApp  push =new XingeApp(Long.getLong(iosKey),iosSercetKey);
        ClickAction clickAction=new ClickAction();
        clickAction.setActionType(ClickAction.TYPE_ACTIVITY);
        clickAction.setActivity("123");
        Style style = new Style(0, 1, 1, 1, 1, 1, 0, 1);
        Message mess = new Message();
        mess.setType(Message.TYPE_NOTIFICATION);
        mess.setStyle(style);
        mess.setTitle("考勤签到提醒");
        mess.setContent("离上班时间还有10分钟");
        mess.setAction(clickAction);
        JSONObject ret = pushAndroid.pushSingleAccount (0, account, mess);



        JSONObject contentTest = new JSONObject();
        JSONObject obj = new JSONObject();
        JSONObject aps = new JSONObject();
        contentTest.put("title", "考勤签到提醒");//标题
        contentTest.put("body", "离上班时间还有10分钟");//内容
        aps.put("badge", 1);
        aps.put("alert", contentTest);
        aps.put("sound", "beep.wav");
        obj.put("aps", aps);
        MessageIOS messageIOS=new MessageIOS();
        messageIOS.setRaw(obj.toString());

        JSONObject ret3 =push.pushSingleAccount(0,account,messageIOS,XingeApp.IOSENV_PROD);
    }

    //数组去重复
    static String[] getDistinct(String num[]) {
        List<String> list = new java.util.ArrayList<String>();
        for (int i = 0; i < num.length; i++) {
            if (!list.contains(num[i])) {//如果list数组不包括num[i]中的值的话，就返回true。
                list.add(num[i]); //在list数组中加入num[i]的值。已经过滤过。
            }
        }
        return list.toArray(new String[0]);
    }


    public String getMachineCode12() {
        String machineCode = null;
        try {
            SysPara para = sysParaMapper.querySysPara("PUSH_MNO");
            if (para != null && !StringUtils.checkNull(para.getParaValue())) {
                machineCode = para.getParaValue().substring(0, 12);
            } else {
                machineCode = MachineCode.get16CharMacs() == null ? "" : MachineCode.get16CharMacs().get(0);
            }
        } catch (Exception e) {
        }
        return machineCode;
    }

}
